﻿using System.ComponentModel;
using System.Reflection;

namespace Om.Core.Extension;

public static class DescriptionHelper
{
    /// <summary>
    /// 获取枚举的描述
    /// 没有[Description]返回Name
    /// </summary>
    /// <param name="value"></param>
    /// <returns></returns>
    public static string GetDescriptionOrName(this System.Enum value)
    {
        FieldInfo field = value.GetType().GetField(value.ToString());
        if (field != null)
        {
            var attributes = field.GetCustomAttributes(typeof(DescriptionAttribute), false) as DescriptionAttribute[];
            if (attributes != null && attributes.Length > 0)
            {
                return attributes[0].Description;
            }
        }
        // 如果没有描述则返回枚举名称
        return value.ToString();
    }

    /// <summary>
    /// 获取成员的描述
    /// 没有[Description]返回Name
    /// </summary>
    /// <param name="info"></param>
    /// <returns></returns>
    public static string GetDescriptionOrName(this MemberInfo info)
    {
        if (info != null)
        {
            var attributes = info.GetCustomAttributes(typeof(DescriptionAttribute), false) as DescriptionAttribute[];
            if (attributes != null && attributes.Length > 0)
            {
                return attributes[0].Description;
            }
        }
        // 如果没有描述则返回枚举名称
        return info?.Name ?? "";
    }
}